package pony.controller;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pony.model.Dog;

/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String myEmail;
    private String myPhone;
    private String myAddress;
	
    // 注意! Container一定會呼叫這個無參數的建構子!
    public HelloServlet() {
        super();
    }
    
    // 可以在HttpServlet的子類別中宣告有參數的建構子，前提是仍然有無參數的建構子!
    public HelloServlet(String s) {
    	super();
    }
    
    // 可以覆寫無參數的 init()方法
    @Override
    public void init() {
    	ServletConfig servConfig = getServletConfig();  // 取得ServletConfig物件參照
    	Enumeration<String> enume = servConfig.getInitParameterNames();
    	while(enume.hasMoreElements()) {
    		if(enume.nextElement().equals("myemail"))
    			myEmail = servConfig.getInitParameter("myemail");
    		if(enume.nextElement().equals("myphone")) 
    			myPhone = servConfig.getInitParameter("myphone");
    		if(enume.nextElement().equals("myaddress")) 
    			myAddress = servConfig.getInitParameter("myaddress");
    	}
    	
    	// 從DD中取得Servlet初始參數後，將其設定為Context作用域的Attribute
    	ServletContext context = getServletContext();
    	context.setAttribute("myemail", myEmail);
    	context.setAttribute("myphone", myPhone);
    	context.setAttribute("myaddress", myAddress);
    }
    
    @Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // 先設定以UTF-8編碼來取得Client端的請求參數
		
		response.setContentType("text/html; charset=UTF-8");  // 設定回應物件的MIME Type與編碼
		request.setAttribute("gretting", "歡迎來到我的動態網站!");
		
		String dogNameValue = request.getParameter("dogName");
		String dogColorValue = request.getParameter("dogColor");
		// String likeDog = request.getParameter("dog");
		Dog userDog = new Dog(dogNameValue, dogColorValue);
		request.setAttribute("dog", userDog);
		
		// 把請求轉向給JSP
		RequestDispatcher dispatcher = request.getRequestDispatcher("./JSPs/sayhello.jsp");
		dispatcher.forward(request, response);
		
//		PrintWriter out = response.getWriter();
//		out.println("Hello! This is my dynamic web site.");
		
	}

}
